local skynet = require "skynet"

local s = require "service"
local game_cmd = require "cmd_def"


local function login(source, fd, msg)
    local username = msg.username
    local pwd = msg.password
    local node = skynet.getenv("node")
    local gate = source

    -- 校验用户名密码
    local isok, userinfo = skynet.call("mysql_node", "lua", "query_player_base_info", username, pwd)
    skynet.error("login call mysql:", isok, userinfo)
    if not isok then
        return false, "no user:" .. username
    end
    if pwd ~= userinfo.password then
        return false, "error password"
    end

    -- 发给agent_mgr
    local uid = userinfo.uid
    local isok, agent = skynet.call("agent_mgr", "lua", "login", uid, node, gate)
    if not isok then
        return false
    end

    -- 回应gate
    local isok = skynet.call(gate, "lua", "sure_login", fd, uid, agent)
    if not isok then
        return false
    end

    userinfo.password = nil
    userinfo.nickname = username.nickname or "default_nick_name"
    skynet.send(gate, "lua", "send_by_fd", fd, game_cmd.SERVER_CMD.LOGIN_RESPONSE, {
        error_code = game_cmd.ERROR_CODE.SUCCESS,
        player_base_info = userinfo
    })

    return true
end

s.CLIENT_CMD_HANDLER = {
    [game_cmd.CLIENT_CMD.LOGIN] = login
}

s.resp.client = function(source, fd, cmd, msg)
    local func = s.CLIENT_CMD_HANDLER[cmd]
    if func then
        local success, ret_msg = func(source, fd, msg)
        if not success then
            skynet.send(source, "lua", "send_by_fd", fd, game_cmd.SERVER_CMD.COMMON, {
                error_code = game_cmd.ERROR_CODE.PERMISSION_DENIED,
                cmd = cmd,
                msg = ret_msg or "failed request"
            })
        end
    else
        skynet.error(s.name .. " node_id:" .. s.id .. " no func, cmd:" .. cmd)
    end
end


s.start(...)